<template>
  <div class="article-detail">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 文章内容 -->
    <div v-else-if="article" class="article-layout">
      <!-- 左侧固定交互栏 -->
      <article-side-actions
        :article-id="article.id"
        :like-count="article.likeCount"
        :comment-count="article.commentCount"
        :collect-count="article.collectCount"
        :is-liked="interactionStatus.isLiked"
        :is-collected="interactionStatus.isCollected"
        :is-logged-in="isLoggedIn"
        @like="handleLike"
        @collect="handleCollect"
        @share="handleShare"
        @comment-count-change="handleCommentCountChange"
        @toggle-comment-drawer="toggleCommentDrawer"
      />
      <!-- 主内容区域 -->
      <div class="article-main">
        <!-- 文章头部信息 -->
        <article-header
          :article="article"
          :interaction-status="interactionStatus"
          @like="handleLike"
          @collect="handleCollect"
          @follow="handleFollow"
          @share="handleShare"
        />

        <!-- 文章正文 -->
        <article-body :article="article" />

        <!-- 评论区 -->
        <comment-section
          v-if="article"
          :article-id="article.id"
          :comment-count="article.commentCount"
          @comment-count-change="handleCommentCountChange"
        />
      </div>

      <!-- 右侧边栏 -->
      <div class="article-sidebar">
        <!-- 文章目录 -->
        <article-toc ref="tocRef" :auto-generate="true" :max-level="4" />

        <!-- 相关文章推荐 -->
        <related-articles
          v-if="relatedArticles.length > 0"
          :articles="relatedArticles"
        />
      </div>

      <!-- 评论拽屉 -->
      <el-drawer
        v-model="commentDrawerVisible"
        title="文章评论"
        direction="rtl"
        size="600px"
        :with-header="true"
        :modal="true"
        :lock-scroll="false"
        :close-on-click-modal="true"
        :close-on-press-escape="true"
        :before-close="handleDrawerBeforeClose"
        :z-index="2000"
        class="comment-drawer"
      >
        <div class="comment-drawer-content">
          <CommentTree
            v-if="article"
            :article-id="article.id"
            :max-level="2"
            :children-limit="5"
            :page-size="10"
            :flat-replies="true"
            :reply-sort-type="1"
            @comment-count-change="handleCommentCountChange"
          />
        </div>
      </el-drawer>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-result
        icon="warning"
        title="文章不存在"
        sub-title="请检查文章链接是否正确"
      >
        <template #extra>
          <el-button type="primary" @click="$router.push('/user/home')">
            返回首页
          </el-button>
        </template>
      </el-result>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserAuthStore } from "@/store/modules/userAuth";
import { followUserApi } from "@/api/user-profile";
import {
  getUserArticleDetailApi,
  getUserInteractionStatusApi,
  likeUserArticleApi,
  collectUserArticleApi,
  getRelatedArticlesApi,
  type UserArticleDetailResponse,
  type UserInteractionStatus,
  type RelatedArticleInfo,
  UserArticleUtils
} from "@/api/user-article";
import { SeoUtil } from "@/utils/seo";

// 组件导入
import ArticleHeader from "./components/ArticleHeader.vue";
import ArticleBody from "./components/ArticleBody.vue";
import RelatedArticles from "./components/RelatedArticles.vue";
import ArticleToc from "./components/ArticleToc.vue";
import CommentSection from "./components/CommentSection.vue";
import ArticleSideActions from "./components/ArticleSideActions.vue";
import { CommentTree } from "@/components/UserComment";

defineOptions({
  name: "UserArticleDetail"
});

const route = useRoute();
const router = useRouter();
const userAuthStore = useUserAuthStore();

// 响应式数据
const loading = ref(true);
const article = ref<UserArticleDetailResponse | null>(null);
const interactionStatus = ref<UserInteractionStatus>({
  isLiked: false,
  isCollected: false,
  isFollowedAuthor: false
});
const relatedArticles = ref<RelatedArticleInfo[]>([]);
const commentDrawerVisible = ref(false);
// 滚动位置状态管理
const savedScrollPosition = ref({ top: 0, left: 0 });

const tocRef = ref();

// 计算属性
const articleId = computed(() => {
  const id = parseInt(route.params.id as string);
  return UserArticleUtils.validateArticleId(id) ? id : null;
});

const isLoggedIn = computed(() => userAuthStore.isLoggedIn);

// 开发环境标识
const isDev = computed(() => import.meta.env.DEV);

// 方法
const loadArticleDetail = async () => {
  if (!articleId.value) {
    loading.value = false;
    return;
  }

  try {
    loading.value = true;

    // 获取文章详情
    const response = await getUserArticleDetailApi(articleId.value);
    article.value = (response as any)?.data || response;

    // 如果用户已登录，获取交互状态
    if (isLoggedIn.value) {
      await loadInteractionStatus();
    }

    // 获取相关文章推荐
    await loadRelatedArticles();

    // 更新页面标题和SEO信息
    updatePageMeta();

    // 延迟刷新目录，确保内容已经增强完成
    setTimeout(() => {
      if (tocRef.value?.refreshToc) {
        tocRef.value.refreshToc();
        console.log("🔄 已刷新文章目录");
      }
    }, 200);
  } catch (error) {
    console.error("获取文章详情失败:", error);
    ElMessage.error(UserArticleUtils.formatErrorMessage(error));
    article.value = null;
  } finally {
    loading.value = false;
  }
};

const loadInteractionStatus = async () => {
  if (!articleId.value || !isLoggedIn.value) return;

  try {
    const response = await getUserInteractionStatusApi(articleId.value);
    interactionStatus.value = (response as any)?.data || response;
  } catch (error) {
    console.error("获取交互状态失败:", error);
    // 不显示错误消息，因为这不是关键功能
  }
};

const loadRelatedArticles = async () => {
  if (!articleId.value) return;

  try {
    const response = await getRelatedArticlesApi(articleId.value, 3);
    relatedArticles.value = (response as any)?.data || response || [];
  } catch (error) {
    console.error("获取相关文章失败:", error);
    // 不显示错误消息，相关文章推荐是可选功能
  }
};

const updatePageMeta = async () => {
  if (!article.value) return;

  try {
    // 获取文章结构化数据
    const structuredData = await SeoUtil.getArticleStructuredData(
      article.value.id
    );

    // 使用SEO工具类设置页面SEO
    const seoInfo = UserArticleUtils.formatSeoInfo(article.value);
    SeoUtil.setPageSeo({
      title: article.value.title,
      description: seoInfo.description,
      keywords: seoInfo.keywords,
      image: seoInfo.ogImage,
      type: "article",
      author: article.value.author?.nickName || article.value.author?.userName,
      publishTime: article.value.publishTime,
      updateTime: article.value.publishTime,
      structuredData: structuredData || undefined
    });
  } catch (error) {
    console.error("文章SEO设置失败:", error);
  }
};

// 事件处理
const handleLike = async () => {
  if (!articleId.value) return;

  if (!isLoggedIn.value) {
    ElMessageBox.confirm("点赞功能需要登录，是否前往登录页面？", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "info"
    })
      .then(() => {
        router.push("/user/login");
      })
      .catch(() => {
        // 用户取消
      });
    return;
  }

  try {
    const newLikeStatus = !interactionStatus.value.isLiked;

    await likeUserArticleApi(articleId.value, newLikeStatus);

    // 更新本地状态
    interactionStatus.value.isLiked = newLikeStatus;
    if (article.value) {
      article.value.likeCount += newLikeStatus ? 1 : -1;
    }

    ElMessage.success(newLikeStatus ? "点赞成功" : "取消点赞成功");
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error(UserArticleUtils.formatErrorMessage(error));
  }
};

const handleCollect = async () => {
  if (!articleId.value) return;

  if (!isLoggedIn.value) {
    ElMessageBox.confirm("收藏功能需要登录，是否前往登录页面？", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "info"
    })
      .then(() => {
        router.push("/user/login");
      })
      .catch(() => {
        // 用户取消
      });
    return;
  }

  try {
    const newCollectStatus = !interactionStatus.value.isCollected;

    await collectUserArticleApi(articleId.value, newCollectStatus);

    // 更新本地状态
    interactionStatus.value.isCollected = newCollectStatus;
    if (article.value) {
      article.value.collectCount += newCollectStatus ? 1 : -1;
    }

    ElMessage.success(newCollectStatus ? "收藏成功" : "取消收藏成功");
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error(UserArticleUtils.formatErrorMessage(error));
  }
};

const handleFollow = async () => {
  if (!article.value || !article.value.author) return;

  if (!isLoggedIn.value) {
    ElMessageBox.confirm("关注功能需要登录，是否前往登录页面？", "提示", {
      confirmButtonText: "去登录",
      cancelButtonText: "取消",
      type: "info"
    })
      .then(() => {
        router.push("/user/login");
      })
      .catch(() => {
        // 用户取消
      });
    return;
  }

  // 不能关注自己
  if (article.value.author.userId === userAuthStore.userId) {
    ElMessage.warning("不能关注自己");
    return;
  }

  try {
    const newFollowStatus = !interactionStatus.value.isFollowedAuthor;
    console.log(
      `👥 关注作者操作 - 用户ID: ${article.value.author.userId}, 新状态: ${newFollowStatus}`
    );

    const response = await followUserApi({
      userId: article.value.author.userId,
      isFollow: newFollowStatus
    });

    if (response.code === 200) {
      // 更新本地状态
      interactionStatus.value.isFollowedAuthor = newFollowStatus;
      if (article.value.author) {
        article.value.author.isFollowed = newFollowStatus;
      }

      ElMessage.success(newFollowStatus ? "关注成功" : "取消关注成功");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("关注作者失败:", error);
    ElMessage.error(UserArticleUtils.formatErrorMessage(error));
  }
};

const handleShare = async () => {
  if (!article.value) return;

  const shareData = UserArticleUtils.getShareData(article.value);

  // 检查是否支持原生分享API
  if (UserArticleUtils.checkShareApiSupport()) {
    try {
      await navigator.share(shareData);
    } catch (error) {
      // 用户取消分享或不支持，fallback到复制链接
      await copyLink();
    }
  } else {
    // 不支持原生分享API，复制链接
    await copyLink();
  }
};

const copyLink = async () => {
  if (!articleId.value) return;

  const success = await UserArticleUtils.copyArticleLink(articleId.value);
  if (success) {
    ElMessage.success("文章链接已复制到剪贴板");
  } else {
    ElMessage.error("复制链接失败");
  }
};

// 评论数量变化处理
const handleCommentCountChange = (count: number) => {
  if (article.value) {
    article.value.commentCount = count;
    console.log(`📝 评论数量更新: ${article.value.commentCount}`);
  }
};

// 切换评论拽屉显示状态
// 解决问题：拽屉弹出时文章滚动到顶部的问题
// 通过保存和恢复滚动位置来解决
const toggleCommentDrawer = () => {
  if (!commentDrawerVisible.value) {
    // 打开拽屉前保存当前滚动位置
    savedScrollPosition.value = {
      top: window.pageYOffset || document.documentElement.scrollTop,
      left: window.pageXOffset || document.documentElement.scrollLeft
    };
    console.log("📎 拽屉打开前保存滚动位置:", savedScrollPosition.value);
  }
  commentDrawerVisible.value = !commentDrawerVisible.value;
};

// 处理拽屉关闭前操作，保持滚动位置
const handleDrawerBeforeClose = (done: () => void) => {
  console.log("📏 拽屉关闭前，保存的滚动位置:", savedScrollPosition.value);

  // 关闭拽屉
  done();

  // 在下一个事件循环中恢复滚动位置
  setTimeout(() => {
    window.scrollTo({
      top: savedScrollPosition.value.top,
      left: savedScrollPosition.value.left,
      behavior: "instant" // 使用 instant 避免动画干扰
    });
    console.log("✅ 滚动位置已恢复到:", savedScrollPosition.value);
  }, 50);
};

// 键盘事件处理
const handleKeyDown = (event: KeyboardEvent) => {
  // ESC 键关闭评论抽屉
  if (event.key === "Escape" && commentDrawerVisible.value) {
    event.preventDefault();
    commentDrawerVisible.value = false;
  }
};

// 监听路由变化
watch(
  () => route.params.id,
  () => {
    if (route.name === "UserArticleDetail") {
      // 文章切换时滚动到顶部
      window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
      loadArticleDetail();
    }
  }
);

// 监听登录状态变化
watch(isLoggedIn, newValue => {
  if (newValue && articleId.value) {
    loadInteractionStatus();
  }
});

// 监听评论拽屉状态变化，确保滚动位置不受影响
watch(commentDrawerVisible, (newValue, oldValue) => {
  if (!newValue && oldValue) {
    // 拽屉关闭时，在下一个循环中恢复滚动位置
    setTimeout(() => {
      if (
        savedScrollPosition.value.top > 0 ||
        savedScrollPosition.value.left > 0
      ) {
        window.scrollTo({
          top: savedScrollPosition.value.top,
          left: savedScrollPosition.value.left,
          behavior: "instant"
        });
        console.log("🔄 监听器恢复滚动位置:", savedScrollPosition.value);
      }
    }, 100);
  }
});

// 生命周期
onMounted(() => {
  // 确保页面滚动到顶部
  window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
  loadArticleDetail();

  // 添加键盘事件监听
  document.addEventListener("keydown", handleKeyDown);
});

// 组件销毁时清理事件监听
onBeforeUnmount(() => {
  document.removeEventListener("keydown", handleKeyDown);
});
</script>

<style scoped lang="scss">
@use "@/styles/user-theme.scss" as *;

@import url("@/styles/unified-code-styles.css");

/* 中等桌面屏幕适配 */
@media screen and (width <= 1400px) and (width >= 901px) {
  .article-sidebar {
    width: 240px;
  }
}

/* 响应式设计 - 平板端 */
@media screen and (width <= 1000px) {
  .article-layout {
    flex-direction: column;
  }

  .article-sidebar {
    position: static;
    top: auto;
    order: 2; /* 在平板端将侧边栏移到底部 */
    width: 100%;
    height: auto;
    padding: 20px 0;
    overflow: visible;
  }

  .article-detail {
    max-width: 900px;
  }
}

/* 移动端适配 - 以iPhone XR为基准 */
@media screen and (width <= 767px) {
  .article-detail {
    padding: 0 !important;
    margin: 0 !important;
  }

  .article-layout {
    flex-direction: column !important;
    gap: 0 !important;
  }

  .article-sidebar {
    position: static !important;

    /* 移动端侧边栏恢复垂直布局 */
    display: flex !important;
    flex-direction: column !important;
    gap: 16px !important;
    order: 2 !important; /* 确保在主内容之后 */
    width: 100% !important;
    height: auto !important;
    padding: 16px !important;
    margin-top: 16px !important;
    overflow: visible !important;
    background: #fff !important;
    border-top: 1px solid #e9ecef !important;
  }

  .article-main {
    padding: 16px !important;
    margin: 0 !important;
    border-radius: 0 !important;
    box-shadow: none !important;
  }

  .loading-container {
    padding: 24px 16px !important;
    margin: 16px !important;
    border-radius: 8px !important;
  }

  .error-container {
    padding: 24px 16px !important;
    margin: 16px !important;
    border-radius: 8px !important;
  }
}

/* 小屏手机适配 */
@media screen and (width <= 375px) {
  .article-main {
    padding: 12px !important;
  }

  .article-sidebar {
    padding: 12px !important;
  }

  .loading-container {
    padding: 20px 12px !important;
    margin: 12px !important;
  }

  .error-container {
    padding: 20px 12px !important;
    margin: 12px !important;
  }
}

/* iPhone XR 专用优化 */
@media (width <= 414px) and (height <= 896px) {
  .article-detail {
    padding-right: max(0px, env(safe-area-inset-right)) !important;
    padding-bottom: env(safe-area-inset-bottom) !important;
    padding-left: max(0px, env(safe-area-inset-left)) !important;
  }

  .article-main {
    padding-right: max(16px, env(safe-area-inset-right)) !important;
    padding-left: max(16px, env(safe-area-inset-left)) !important;
  }

  .article-sidebar {
    padding-right: max(16px, env(safe-area-inset-right)) !important;
    padding-left: max(16px, env(safe-area-inset-left)) !important;
  }

  .loading-container {
    margin-right: max(16px, env(safe-area-inset-right)) !important;
    margin-left: max(16px, env(safe-area-inset-left)) !important;
  }

  .error-container {
    margin-right: max(16px, env(safe-area-inset-right)) !important;
    margin-left: max(16px, env(safe-area-inset-left)) !important;
  }
}

.article-detail {
  max-width: 1400px;
  padding: 20px;
  margin: 20px auto;

  // 移动端适配
  @media (width <= 767px) {
    max-width: 100%;
    padding: 12px 16px;
    margin: 0;
  }

  @media (width <= 374px) {
    padding: 8px 12px;
  }

  // iPhone XR 专用优化
  @media (width <= 414px) and (height <= 896px) {
    padding-right: max(16px, env(safe-area-inset-right));
    padding-bottom: env(safe-area-inset-bottom);
    padding-left: max(16px, env(safe-area-inset-left));
  }
}

.loading-container {
  max-width: 800px;
  padding: 40px 20px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.error-container {
  max-width: 800px;
  padding: 40px 20px;
  margin: 0 auto;
  text-align: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.article-layout {
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.article-main {
  flex: 1;
  min-width: 0; /* 防止内容溢出 */
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}

.article-sidebar {
  position: sticky;
  top: 20px;
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  gap: 20px;
  width: 280px;
  height: calc(100vh - 40px);
  padding: 40px 0 20px;
  padding-left: 20px;
  margin-top: 0;
  margin-left: -20px;
  overflow-y: auto;

  // 添加微妙的左侧边框以强化浮动效果
  border-left: 1px solid rgb(0 0 0 / 4%);

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
  }

  &::-webkit-scrollbar-thumb {
    background: rgb(0 0 0 / 10%);
    border-radius: 2px;

    &:hover {
      background: rgb(0 0 0 / 20%);
    }
  }
}

.comment-section {
  padding-top: 24px;
  margin-top: 40px;
  border-top: 1px solid var(--el-border-color-light);

  // 移动端为底部交互栏预留空间
  @media screen and (width <= 999px) {
    margin-bottom: 80px; // 为底部交互栏预留空间
  }
}

// 评论抽屉样式
:deep(.el-drawer) {
  // 确保抽屉不影响主页面滚动
  position: fixed;
  z-index: 2000;

  .el-drawer__header {
    padding: 16px 20px;
    margin-bottom: 0;
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    box-shadow: 0 1px 4px rgb(0 0 0 / 8%);

    .el-drawer__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  .el-drawer__body {
    position: relative;
    padding: 0;
    // 确保抽屉内部独立滚动
    overflow: hidden;
    background: #f8f9fa;
  }

  // 抽屉容器样式优化
  .el-drawer__container {
    // 防止抽屉影响主页面滚动
    overflow: hidden;
  }
}

// 评论抽屉遮罩层优化
:deep(.el-overlay) {
  // 确保遮罩层不会阻止主页面的滚动状态
  background-color: rgb(0 0 0 / 30%) !important;
}

.comment-drawer-content {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  background: #fff;

  :deep(.comment-tree) {
    flex: 1;
    padding: 0 20px;
    overflow-y: auto;
    scrollbar-color: #c1c1c1 transparent;
    // 优化滚动条样式
    scrollbar-width: thin;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #c1c1c1;
      border-radius: 3px;
      transition: background-color 0.3s ease;

      &:hover {
        background-color: #a1a1a1;
      }
    }
  }
}
</style>
